import React from 'react';
import { Button, message } from 'antd';
import pageTabUtil from '@/utils/pageTabUtil';
import { withRouter } from 'umi';
import { BottomAction } from '@/components';
import { useRequest } from '@/hooks';
import { updateInformal } from '../../services';

const noop = () => {};
function BottomActionContainer({ location, params, form, data = {}, openAll = noop, onBeforeSubmit = noop }) {
    const { query } = location;

    const { run, loading } = useRequest(updateInformal, {
        manual: true
    });
    const [beforeSubmitLoading, setBeforeSubmitLoading] = React.useState(false);

    return (
        <BottomAction>
            <Button
                onClick={() => {
                    pageTabUtil.goBack();
                }}
            >
                取消
            </Button>
            <Button
                loading={loading || beforeSubmitLoading}
                type="primary"
                onClick={async () => {
                    form.validateFieldsAndScroll({ force: true }, async (err, values) => {
                        if (err) {
                            openAll();
                            setTimeout(() => {
                                form.validateFieldsAndScroll({ scroll: { alignWithTop: true } });
                            });
                            return;
                        }
                        try {
                            setBeforeSubmitLoading(true);
                            await onBeforeSubmit();
                        } catch (e) {
                            console.log(`onBeforeSubmit reject :${e}`);
                            return;
                        } finally {
                            setBeforeSubmitLoading(false);
                        }
                        // 服务端必要字段
                        const requireParams = {
                            employeeCode: data?.employeeCode,
                            status: query.status || data?.status,
                            assessId: query.assessId
                        };
                        let finalParams = { ...requireParams, ...params };

                        if (params instanceof Function) {
                            finalParams = { ...requireParams, ...(await params(values)) };
                        }

                        const res = (await run(finalParams)) || {};
                        const { code } = res;

                        if (code === 10000) {
                            message.success('操作成功！');
                            pageTabUtil.goBack();
                        } else {
                            message.error(res.msg || '操作失败！');
                        }
                    });
                }}
            >
                确定
            </Button>
        </BottomAction>
    );
}

export default withRouter(BottomActionContainer);
